//
//  LBNetwork.m
//  V-Learn
//
//  Created by Apple on 2018/12/25.
//  Copyright © 2018 yxk. All rights reserved.
//

#import "LBNetwork.h"
#import "AFNetworking.h"
#import "UserModel.h"
#import "SVProgressHUD.h"
#import "LBNavigationController.h"
@implementation LBNetwork

+(void)POST:(NSString *)url parameters:(NSDictionary *)parameter isShowHUD:(BOOL)isShowHUD HUDString:(NSString *)string isToken:(BOOL)isToken success:(BRSuccess)success error:(BRError)erro{
    if (isShowHUD) {
        if (string == nil) {
            string = @"正在加载...";
        }
        [SVProgressHUD showWithStatus:string];
    }
    
    AFHTTPSessionManager * manage = [AFHTTPSessionManager manager];
    manage.requestSerializer = [AFJSONRequestSerializer serializer];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    manage.requestSerializer = [AFJSONRequestSerializer serializer];
    manage.responseSerializer = [AFJSONResponseSerializer serializer];
      [manage.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manage.requestSerializer.timeoutInterval = 60.0f;
    [manage.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];//无条件的信任服务器上的证书
    AFSecurityPolicy *securityPolicy =  [AFSecurityPolicy defaultPolicy];// 客户端是否信任非法证书
    securityPolicy.allowInvalidCertificates = NO;// 是否在证书域字段中验证域名
    securityPolicy.validatesDomainName = NO;manager.securityPolicy = securityPolicy;
    
    
    
    
    if (isToken) {
        UserModel * model = [UserModel getUserModel];
        [manage.requestSerializer setValue:model.token forHTTPHeaderField:@"token"];
    }
    if (![url hasPrefix:@"http"]) {
        url = [NSString stringWithFormat:@"%@%@",Serve_URL,url];
    }
    [manage POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * dict =  [self json:responseObject];
        if (success) {
            NSString * code = [NSString stringWithFormat:@"%@",dict[@"code"]];
            if ([code isEqualToString:@"500"]) {
                // 去登录
                UIViewController * vc = [self topViewController];
                if (![vc isKindOfClass:NSClassFromString(@"LoginVC")]) {
                    UIViewController * login = [[NSClassFromString(@"LoginVC") alloc] init];
                    LBNavigationController * nav = [[LBNavigationController alloc] initWithRootViewController:login];
                    [vc presentViewController:nav animated:YES completion:nil];
                }
                [SVProgressHUD showInfoWithStatus:@"登录失效"];
                [SVProgressHUD dismissWithDelay:1.5];
                return;
            }
            if(![code isEqualToString:@"200"]){
                NSString * msg = dict[@"msg"];
                if (![msg isKindOfClass:[NSString class]]) {
                    msg = @"获取失败";
                }
                if (kStringIsEmpty(msg)) {
                    msg = @"暂无数据";
                }
                if ([msg isEqualToString:@"暂无数据"]) {
                    
                }else{
                    [SVProgressHUD showErrorWithStatus:msg];
                    [SVProgressHUD setBackgroundColor:BRRGBColor(112, 112, 112, 112)];
                    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                    [SVProgressHUD dismissWithDelay:2];
                }
                
            }
            success(task,dict);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        if (error) {
            NSData *data = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
//            NSLog(@"%@&&&&&&%@",url,[[NSString alloc] initWithData:data encoding:(NSUTF8StringEncoding)]);
            [SVProgressHUD showErrorWithStatus:@"连接服务器失败"];
            erro(task,error);
        }
    }];
    
}
+ (NSDictionary *)json:(id)data{
    NSDictionary * dict;
    NSError * error;
    dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:&error];
    if (error) {
        // data 转字典 失败
        dict = @{@"code":@"123",@"msg":[error localizedDescription]};
        NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
//        NSLog(@"原始json:%@",str);
    }
    return dict;
}

+ (void)UploadImage:(NSArray *)imageArray parameters:(NSDictionary *)dict success:(BRSuccess)success error:(BRError)erro{
    if (imageArray == nil) {
        success(nil,[NSMutableArray array]);
        return;
    }
    if (imageArray.count == 0) {
        success(nil,[NSMutableArray array]);
        return;
    }
    NSMutableArray * imageUrl = [NSMutableArray array];
    
    for (int i = 0; i < imageArray.count; i++) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        UserModel * model = [UserModel getUserModel];
        [manager.requestSerializer setValue:model.token forHTTPHeaderField:@"token"];
        [manager POST:[NSString stringWithFormat:@"%@%@",Serve_URL,@"index/upload"] parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            UIImage * image = imageArray[i];
            NSData * data = UIImageJPEGRepresentation(image, 0.7);
            [formData appendPartWithFileData:data name:@"file" fileName:@"file.png" mimeType:@"image/jpeg"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary * dict =  [self json:responseObject];
            NSString * code = [NSString stringWithFormat:@"%@",dict[@"code"]];
            if ([code isEqualToString:@"200"]) {
                [imageUrl addObject:dict[@"response"][@"fileurl"]];
            }
            
            if (imageArray.count == imageUrl.count && success) {
                success(task,imageUrl);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (error) {
                erro(task,error);
//                NSLog(@"%@",erro);
                [SVProgressHUD showErrorWithStatus:@"链接服务器失败"];
                [SVProgressHUD dismissWithDelay:1];
            }
        }];
        
    }
}

+ (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

+ (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

+ (void)POSTWithSession:(NSString *)url parameters:(NSDictionary *)parameter isShowHUD:(BOOL)isShowHUD HUDString:(NSString *)string isToken:(BOOL)isToken success:(BRSuccess)success error:(BRError)erro{
    if (isShowHUD) {
        if (string == nil) {
            string = @"正在加载...";
        }
        [SVProgressHUD showWithStatus:string];
        [SVProgressHUD setDefaultStyle:SVProgressHUDMaskTypeGradient];
    }
    if (![url hasPrefix:@"http"]) {
        url = [NSString stringWithFormat:@"%@%@",Serve_URL,url];
        
    }
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    request.HTTPMethod = @"POST";
    NSData * data = [self getData:parameter];
    [request setHTTPBody:data];
    [request setValue:[NSString stringWithFormat:@"%d",(int)data.length] forHTTPHeaderField:@"Content-Length"];
    if (isToken) {
        UserModel * model = [UserModel getUserModel];
        [request setValue:model.token forHTTPHeaderField:@"token"];
    }
    NSURLSession * session = [NSURLSession sharedSession];
    
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            if (data) {
                NSDictionary * dict =  [self json:data];
                NSString * code = [NSString stringWithFormat:@"%@",dict[@"code"]];
                if ([code isEqualToString:@"500"]) {
                    // 去登录
                    UIViewController * vc = [self topViewController];
//                    NSLog(@"%@",vc);
                    if ([vc isKindOfClass:NSClassFromString(@"LoginVC")]) {
                    }else{
                        UIViewController * login = [[NSClassFromString(@"LoginVC") alloc] init];
                        [vc presentViewController:login animated:YES completion:nil];
                        return;
                    }
                }
                
                if(![code isEqualToString:@"200"]){
                    [SVProgressHUD showErrorWithStatus:dict[@"msg"]];
                    [SVProgressHUD dismissWithDelay:1];
                }
                success(nil,dict);
            }
            
            if (error) {
                erro(nil,error);
            }
        });
    }];
    [task resume];
}

+ (NSData *)getData:(NSDictionary *)dict{
    NSMutableString *temMutableString = [NSMutableString stringWithString:@""];
    for(NSString *key in dict.allKeys)
    {
        NSString *temStr = [dict objectForKey:key];
        temStr = [temStr stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];
        temStr = [temStr stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
        [temMutableString appendFormat:@"&%@=%@",key,temStr];
    }
    return [temMutableString dataUsingEncoding:NSUTF8StringEncoding];
}
@end
